<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column
                label="序号"
                type="index"
                :index="indexMethod"
                width="120"
              />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="hAssign(scope.row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="hEdit(scope.row)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="hDel(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件

              current-change: 翻页时执行回调
              size-change: 每页几条 改变执行
              total： 一共有几条数据
              current-page： 当前的页码
              page-size： 每页显示几条
              page-sizes： 可以自己选择的 每页几条 数据
              layout： 整体的布局
              -->
              <el-pagination
                :total="total"
                :current-page="page"
                :page-size="pagesize"
                :page-sizes="[1, 2, 3, 4, 5]"
                layout="sizes,prev,pager,next"
                @current-change="hCurrentChange"
                @size-change="hSizeChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <el-form
        ref="roleForm"
        :rules="rules"
        :model="roleForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">
            确定
          </el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      :title="1 ? '编辑' : '新增'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogPermission"
    >
      <assignPermission
        ref="assignPermission"
        :role-id="roleId"
        @success="hsuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, delRole, addRole, editRole } from '@/api/settings.js'
import assignPermission from './assignPermission'
export default {
  components: { assignPermission },
  data() {
    return {
      showDialogPermission: false,
      isEdit: false,
      showDialog: false,
      roleForm: {
        name: '程序员',
        description: '改变世界'
      },
      time: '',
      pagesize: 5, // 一页5条数据
      page: 1, // 当前页码
      total: 0, // 总条数
      roles: [],
      sum: 0,
      roleId: '',
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hsuccess() {
      this.showDialogPermission = false
      this.$message.success('成功')
    },
    hAssign(id) {
      this.showDialogPermission = true
      this.roleId = id
      this.$nextTick(() => {
        this.$refs.assignPermission.loadgetRoleDetail()
      })
    },
    hClose() {
      this.$refs.roleForm.resetFields()
    },
    async doAdd() {
      try {
        await addRole(this.roleForm)
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
        this.loadRoles()
        this.showDialog = false
        this.$message.success('添加成功')
      } catch (error) {
        console.log(error)
        this.$message.error('添加失败')
      }
    },
    async doEdit() {
      try {
        await editRole(this.roleForm)
        this.loadRoles()
        this.showDialog = false
        this.$message.success('修改成功')
      } catch (error) {
        console.log(error)
        this.$message.error('修改失败')
      }
    },
    hEdit(data) {
      // 加展开运算符是浅拷贝,双向绑定; 深拷贝在开一个新空间.
      this.roleForm = { ...data }
      this.showDialog = true
      this.isEdit = true
    },
    hSubmit() {
      // 兜底校验
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          this.isEdit ? this.hEdit() : this.doAdd()
        }
      })
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
      // 3-1 * 2 + 0 +1
    },
    // hAdd(){
    //   this.time=setInterval( async ()=>{
    //        this.sum++
    //        await addRole({name:'大西瓜',description:`吃了${this.sum}块西瓜`})
    //   },1000)
    // },
    // ding(){
    //      clearInterval(this.time)
    // },
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    async doDel(id) {
      try {
        if (this.roles.length === 1 && this.page > 1) {
          this.page--
        }
        await delRole(id)
        this.$message.success('删除成功')
        this.loadRoles()
      } catch (err) {
        this.$message.error('删除失败')
      }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch((err) => {
          this.$message(err)
        })
    },

    // 更改每页显示几条数据
    hSizeChange(curPagesize) {
      console.log(curPagesize)
      // 1. 更新参数
      this.pagesize = curPagesize
      this.page = 1
      // 2. 重发请求
      this.loadRoles()
    },
    // 自动接收当前的页码
    hCurrentChange(curPage) {
      console.log(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadRoles()
    },
    async loadRoles() {
      try {
        const res = await getRoles({
          page: this.page,
          pagesize: this.pagesize
        })

        this.total = res.data.total
        this.roles = res.data.rows
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>
